'use strict';

app.controller('projectPlanCtrl', ['$scope', '$http', '$modal', '$log', '$location', '$rootScope','lodash','$filter','$timeout', function ($scope, $http, $modal, $log, $location, $rootScope,lodash,$filter,$timeout) {
    $scope.urlProjectPlan = "";   //url中的集成计划
    $scope.urlUser        = "";   //url中的用户
    $scope.urlKeyword     = "";   //url中的关键字
    $scope.urlFinished    = "";   //url中的是否包含已完成
    $rootScope.initBreadcrumb($scope.breadcrumb);
    $scope.breadcrumb.push('项目计划');
    //页面加载时，给headerElement设置元素
    $rootScope.initHeaderElements($scope.settings);
    $scope.settings.searchEle = {
        show: true,                   //显示查询框
        func: function(keyword) {     //点击查询框调用的方法
            $scope.urlKeyword = keyword ? keyword : "";
            getProjectPlanList();
        },
        blurFunc: function(keyword) {
            $scope.urlKeyword = keyword ? keyword : "";
        }
    };
    $scope.settings.dateRadios = {
        show: true,
        radios: config_date_radios,
        init:2,
        func: function (startDate) {
            $scope.info.searchC.startDate=startDate;
            getProjectPlanList();
        }
    }
    var createProjectPlan = {
        show : true,
        label: "创建项目",
        func : function() {
            $scope.createProjectPlan();
        }
    };
    $scope.settings.btnEle.push(createProjectPlan);
    //结束headerElement设置
    
    $scope.allUsers         = [];  //个人全部项目
    $scope.Integrationplans = [];  //全部集成计划数据

    $scope.info = {
        tableScope: {},
        irTrueProjectPlanInfoLock : false,
        statusArray     : [],    //状态数组
        businessArray   : [],    //业务数组
        projectPlanInfo : {},
        searchC: {}, //查询条件
        thdata          : [
            {"thName": "项目"},
            {"thName": "开始日期"},
            {"thName": "上线日期"},
            {"thName": "PDM"},
            {"thName": "Leader"},
            {"thName": "风险"},
            {"thName": "进展"}
        ],      
        page            : {"isTrue": true},
        projectPlanList : {
            "isOperation": {
                "Delete": {
                    "isTrue": true,
                    "msg"   : "删除项目计划"
                }
            },
            "tdName"    : [
                {"name": "projectPlanName"},
                {"name": "projectPlanStartupTime"},
                {"name": "projectPlanOnlineTime"},
                {"name": "projectPlanPdmRealname"},
                {"name": "projectPlanChargerRealname"},
                {"name": "risk"},
                {"name": "projectPlanStatusTbShow"},
            ]
        }
    };
    $scope.settings.switchs.push({
        label: "显示已上线项目计划",
        check: false,
        checkFun: function (check) {
            $scope.info.searchC.showOnline = check;
            getProjectPlanList();
        }
    });
    
    setFondness();
    getStatusAndBusiness();

    getUserList();
    getIntegrationList();
    // containFinished();
    

    //获取偏好设置
    function setFondness() {
        var fondness = getFondness("/api/v1/projectPlan/getProjectPlans");
        if(fondness) {
            $scope.urlUser        = fondness.userAccount ? fondness.userAccount : "";
            $scope.urlProjectPlan = fondness.onlineTime ? fondness.onlineTime : "";
        }
    }

    //获取用户集合
    function getUserList() {
        var url = beetle_auth_url +"/user/?token_id=" + getTokenId();
        $http.get(url).success(function(result) {
            if(result.success) {
                if(result.data) {
                    var accountArray = [{"crtname": "个人全部项目", "id": 0}];
                    angular.forEach(result.data, function(data) {
                        data.crtname = data.realname;
                        accountArray.push(data);
                    });
                    $scope.allUsers = result.data;
                    setHeaderUser(accountArray);
                } else {
                    $rootScope.toasterErrorInfo("获取用户数据错误！");
                }
            } else {
                $rootScope.toasterErrorInfo(result.msg);
            }
        });
    };

    //设置header中的用户（负责人）
    function setHeaderUser(userList) {
        var fondnessAccount = "";
        if($scope.urlUser) {
            var crtAccount = lodash.findWhere(userList, {"account": $scope.urlUser});
            crtAccount.crtname = crtAccount.realname;
            fondnessAccount = crtAccount;
        } else {
            fondnessAccount = {"crtname": "个人全部项目", "id": 0};
        }
        var userSelectEle = {
            status       : true,
            items        : userList,
            prompt       : "个人全部项目",
            selectedItem : fondnessAccount,
            func : function(item) {
                $scope.urlUser = item.account ? item.account : "";
                getProjectPlanList();
            }
        };
        $scope.settings.uiSltEle.push(userSelectEle);
    };

    //获取集成计划集合
    function getIntegrationList() {
        var url = beetle_plan_url +"/integration/getIntegrationPlanList?token_id="+ getTokenId() +"&hasProList=false&isEmergency=1";
        $http.get(url).success(function(result) {
            if(result.success) {
                if(result.data) {
                    var integrationArray = [{"crtname": "全部集成计划", "id": 0}];
                    angular.forEach(result.data, function(data) {
                        data.crtname = data.integration_name;
                        integrationArray.push(data);
                    });
                    $scope.Integrationplans = result.data;
                    setHeaderIntegration(integrationArray);
                } else {
                    $rootScope.toasterErrorInfo("获取集成计划数据错误");
                }
            } else {
                $rootScope.toasterErrorInfo(result.msg);
            }
        });
    };

    //设置header的集成计划
    function setHeaderIntegration(integrationList) {
        var fondnessIntegration = "";
        if($scope.urlProjectPlan) {
            var crtIntegration = lodash.findWhere(integrationList, {"online_date":  $filter('date')(new Date($scope.urlProjectPlan), 'yyyy-MM-dd')});
            crtIntegration.crtname = crtIntegration.integration_name;
            fondnessIntegration = crtIntegration;
        } else {
            fondnessIntegration = {"crtname": "全部集成计划", "id": 0};
        }
        var integrationSelectEle = {
            status       : true,
            width        : "160px",
            items        : integrationList,
            prompt       : "全部集成计划",
            selectedItem : fondnessIntegration,
            func : function(item) {
                $scope.urlProjectPlan = item.online_date ? item.online_date : "";
                getProjectPlanList();
            }
        };
        $scope.settings.uiSltEle.push(integrationSelectEle);
    };

    function containFinished(){
        var list=[{"crtname":"是否包含已完成"},{"crtname":"是","key":"Y"},{"crtname":"否","key":"N"}]
        var selectFinished = {
            status       : true,
            items        : list,
            prompt       : "是否包含已完成的项目",
            selectedItem : list[0],
            func : function(item) {
                $scope.urlFinished=item.key ? item.key : "";
               getProjectPlanList();
            }
        };
        $scope.settings.uiSltEle.push(selectFinished);
    }



    //获取状态&业务数据集
    function getStatusAndBusiness() {
        var url = sys_config_url +"/select/get?type=BRD_STATUS,BRD_BUSINESS";
        $http.get(url).success(function(result) {
            if(result.code == "0") {
                $scope.info.statusArray   = result.data.BRD_STATUS;
                $scope.info.businessArray = result.data.BRD_BUSINESS;
                getProjectPlanList();
            } else {
                $rootScope.toasterErrorInfo(result.desc);
            }
        });
    };

    //获取项目计划数据集
    function getProjectPlanList() {
        var url = matrix_product_url +"/projectPlan/getProjectPlans";

        var urlArray = [
            {"type": "reserveHabit", "param": 1},
            {"type": "tokenId",      "param": getTokenId()},
            {"type": "userAccount",  "param": $scope.urlUser},
            {"type": "keyword",      "param": $scope.urlKeyword},
            {"type": "containFinished",      "param": $scope.urlFinished},
        ];
        if($scope.urlProjectPlan) {
            urlArray.push({"type": "onlineTime",   "param": encodeURIComponent(new Date($scope.urlProjectPlan))});
        }
        if ($scope.info.searchC.showOnline) {
            urlArray.push({"type": "containFinished", "param": $scope.info.searchC.showOnline?"Y":"N"})
        }
        if ($scope.info.searchC.startDate) {
            urlArray.push({"type": "startDate", "param": $scope.info.searchC.startDate})
        }
        url = $rootScope.setUrlParams(url, urlArray);
        $timeout(function () {
            $http.get(url).success(function(result) {
                if(result.code == "0") {
                    angular.forEach(result.data, function(data) {
                        //设置对应状态的中文名称
                        var statusItem = lodash.findWhere($scope.info.statusArray, {key: data.projectPlanStatus});
                        data.projectPlanStatusTbShow = statusItem ? statusItem.value : data.projectPlanStatus;
                        //设置对象业务的中文名称
                        var bussinessItem = lodash.findWhere($scope.info.businessArray, {key: data.projectPlanBusiness});
                        data.projectPlanBusinessTbShow = bussinessItem ? bussinessItem.value : data.projectPlanBusiness;
                        data.projectPlanStartupTime = timestampToTime(data.projectPlanStartupTime, true);
                        data.projectPlanOnlineTime = timestampToTime(data.projectPlanOnlineTime, true);
                    });
                    $scope.info.projectPlanList.datas = result.data;
                } else {
                    $rootScope.toasterErrorInfo(result.desc);
                }
            });
        })

    };

    //点击标题查看项目计划详情
    $scope.editProjectPlan = function (type, info) {
        setStorage('projectPlanBackUrl', $location.url());
        window.location.href = "#/app/plan/summary/" + type + "/" + info.projectPlanId;
    };

    //删除项目计划
    $scope.deleteProjectPlan = function(info) {
        var confirmParams = {
            "titleData" : "提示",
            "bodyData"  : "确定要删除【"+ info.projectPlanName +"】吗？"
        };
        $rootScope.confirmWindow(confirmParams, function(confirm) {
            var postParams = {
                projectPlanIsDel : "0",
                projectPlanId    : info.projectPlanId,
                tokenId          : getTokenId(),
                uplanId          : info.uplanId,
            };
            var url = matrix_product_url +"/projectPlan/saveProjectPlan";
            $http({
                method   : "post",
                url      : url,
                data     : JSON.stringify(postParams),
                headers : {"Content-Type": "application/json"}
            }).success(function(result) {
                if(result.code == "0") {
                    lodash.remove($scope.info.projectPlanList.datas, {projectPlanId: info.projectPlanId});
                    $rootScope.toasterSuccessInfo("删除成功！");
                } else {
                    $rootScope.toasterErrorInfo(result.desc);
                }
            });
        });
    }

    //项目计划上线
    $scope.projectPlanOnline = function (info) {
        var confirmParams = {
            "titleData" : "提示",
            "bodyData"  : "确定要上线【"+ info.projectPlanName +"】吗？"
        };
        $rootScope.confirmWindow(confirmParams,function () {
            console.log(info);
        })
    }

    //创建项目
    $scope.createProjectPlan = function() {
        $rootScope.projectPlanSaveShow(null, $scope.info.statusArray, null, function() {
            getProjectPlanList();
        });
    };
}]);


